package com.computergames.server.server.handler;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.computergames.server.message.ErrorResponseMessage;
import com.computergames.server.message.HasJwtToken;
import com.computergames.server.message.LoginRequestMessage;
import com.computergames.server.message.PingMessage;
import com.computergames.server.util.JWTUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class JWTAuthHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 检查是否为LoginRequestMessage，如果是则直接传递给下一个handler
        if (msg instanceof LoginRequestMessage || msg instanceof PingMessage) {
            ctx.fireChannelRead(msg);
            return;
        }

        // 对于其他消息类型，尝试从请求中获取Token
        String token = ((HasJwtToken) msg).getJwtToken();

        if (token != null) {
            try {
                // 验证Token
                DecodedJWT decodedJWT = JWTUtils.verify(token);
                // 如果验证成功，将消息传递给下一个handler
                ctx.fireChannelRead(msg);
            } catch (JWTVerificationException e) {
                // 如果验证失败，关闭连接或发送错误响应
                ctx.close();
                log.error("Invalid token: {}", token);

                // 或者发送错误消息
                 ctx.writeAndFlush(new ErrorResponseMessage("无效的token"));
            }
        } else {
            // 如果没有找到Token，关闭连接或发送错误响应
            ctx.close();
            log.error("No token provided");
            // 发送错误消息
            ctx.writeAndFlush(new ErrorResponseMessage("token为null"));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
